// 定义webSocketService类
export default class SocketService {
  /**
   * 单列设计模式
   */
  static instance = null

  static get Instance() {
    if (!this.instance) {
      this.instance = new SocketService()
    }
    return this.instance
  }

  // websocket实例
  wss = null

  // 存储回调函数
  callBackMapping = {}

  // 连接服务器
  connect() {
    if (!window.WebSocket) {
      return console.log('你的浏览器不支持webSocket')
    }
    this.wss = new WebSocket('ws://localhost:9998')

    // 事件监听
    this.wss.onopen = () => {
      console.log('连接服务端成功')
    }
    this.wss.onclose = () => {
      console.log('连接失败')
      console.log('尝试重新连接')
      setTimeout(() =>{
        this.connect()
        console.log('重连成功')
      }, 5000)
    }
    // 服务器发送的数据
    this.wss.onmessage = (msg) => {
      // 接受服务端的数据
      let msgData = JSON.parse(msg.data);
      if (this.callBackMapping[msgData.socketType]){
        switch (msgData.action) {
          case 'getData':
            this.callBackMapping[msgData.socketType].call(this, JSON.parse(msgData.data));
            break;
          case  'fullScreen':
            // console.log(msgData)
            this.callBackMapping[msgData.socketType].call(this, msgData);
            break
          case 'themeChange':
            this.callBackMapping[msgData.socketType].call(this, msgData);
        }
      }
    }
  }
  // 回调函数的注册
  registerCallBack(socketType, callback) {
    this.callBackMapping[socketType] = callback
  }

  // 取消回调函数
  unRegisterCallBack(socketType) {
    this.callBackMapping[socketType] = null
  }

  // 发送数据
  send(data){
    if (this.wss.readyState===1){
      this.wss.send(JSON.stringify(data))
    } else {
      setTimeout(()=> {
        this.wss.send(JSON.stringify(data))
      },500)
    }
  }
}